﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Collections.Specialized;
using Intergr8.GoogleVisualization;
using AntiObesity.Utilities.Wire;
using AntiObesity.Base.Managers;
using System.Web.SessionState;

namespace AntiObesity.Services
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://antiobesity-project.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UserHomeGraph : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var tqx = new TQX(context.Request["tqx"]);

            var sb = new StringBuilder();
            sb.Append(tqx.ResponseHandler);
            sb.Append("({");

            sb.AppendFormat("reqId:'{0}',", tqx.ReqId);
            sb.Append("status:'ok',");

            var data = new Table();
            data.AddColumn(DataType.Date, "Date");
            data.AddColumn(DataType.Number, "Calories");
            data.AddColumn(DataType.String, "title1");
            data.AddColumn(DataType.String, "text1");
            data.AddColumn(DataType.Number, "Weight");
            data.AddColumn(DataType.String, "title2");
            data.AddColumn(DataType.String, "text2");

            var userID = context.Session.GetCurrentUser().ID;
            var from = IntakeManager.FindFirstIntakeDate(userID);
            var to = DateTime.Today.Tomorrow();
            var bodyHistories = BodyHistoryManager.GetAll(userID);
            var targetHistories = TargetHistoryManager.GetAll(userID);

            // order of histories are date desc, so the last one is the first height entered
            var weight = bodyHistories.Last().Weight;

            for (var day = from;
                     day < to;
                     day = day.AddDays(1))
            {
                var row = new Row();
                row.AddCell(String.Format("Date({0}, {1}, {2})", day.Year, day.Month - 1, day.Day));

                var consumedCalories = IntakeManager.GetTotalCalories(day, day.Tomorrow(), userID);
                // having formatter as "#.##" makes sure 0.0 will go as undefined to client side, showing nothing for that day
                row.AddCell(consumedCalories.ToString("#.##"));

                row.AddCell(null);
                row.AddCell(null);

                if (bodyHistories.Any(h => h.Date.IsSameDay(day)))
                {
                    weight = bodyHistories.
                        Where(h => h.Date.IsSameDay(day)).
                        Select(h => h.Weight).
                        First();
                }
                row.AddCell(weight.ToString("#.##"));

                if (targetHistories.Any(h => h.Date.IsSameDay(day)))
                {
                    var targetWeight = targetHistories.
                        Where(h => h.Date.IsSameDay(day)).
                        Select(h => h.TargetWeight).
                        First();
                    row.AddCell(String.Format("Target set to {0:#.##} kg ", targetWeight));
                    row.AddCell(null); // no description yet
                }
                else
                {
                    row.AddCell(null);
                    row.AddCell(null);
                }

                data.AddRow(row);
            }
            sb.Append(data.ToJSON());
            sb.Append("})");

            context.Response.Write(sb.ToString());
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}
